from DebugTrace import DebugTrace
import wiringpi
from time import sleep

#
# Analog to digital converter drivers
# for controlling a TI ADC10064
#

class AnalogDigitalConverter(object):
    def __init__(self,s0Pin,s1Pin,intPin,samplePin,debugLevel=1):
        self.s0Pin=s0Pin
        self.s1Pin=s1Pin
        self.intPin=intPin
        self.samplePin=samplePin
        self.input=0
        self.io = wiringpi.GPIO(wiringpi.GPIO.WPI_MODE_SYS)
        self.trace = DebugTrace("ADC",debugLevel)

        #Default to input 0
        self.io.pinMode(self.s0Pin,self.io.OUTPUT)
        self.io.digitalWrite(self.s0Pin,self.io.LOW)
        self.io.pinMode(self.s1Pin,self.io.OUTPUT)
        self.io.digitalWrite(self.s1Pin,self.io.LOW)

        #Default to hold output
        self.io.pinMode(self.samplePin,self.io.OUTPUT)
        self.io.digitalWrite(self.samplePin,self.io.HIGH)

        #Setup intPin as an input
        self.io.pinMode(self.intPin,self.io.INPUT)

    def selectInput(self,inputNum):
        self.input=inputNum
        self.trace.trace(2,"Selected input "+str(inputNum))
        if (inputNum==0):
            self.io.digitalWrite(self.s0Pin,self.io.LOW)
            self.io.digitalWrite(self.s1Pin,self.io.LOW)
        elif (inputNum==1):
            self.io.digitalWrite(self.s0Pin,self.io.HIGH)
            self.io.digitalWrite(self.s1Pin,self.io.LOW)
        elif (inputNum==2):
            self.io.digitalWrite(self.s0Pin,self.io.LOW)
            self.io.digitalWrite(self.s1Pin,self.io.HIGH)
        elif (inputNum==3):
            self.io.digitalWrite(self.s0Pin,self.io.HIGH)
            self.io.digitalWrite(self.s1Pin,self.io.HIGH)
        else:
            self.trace.trace(1,"Invalid!")

    def convert(self):
        busyWork=0
        self.trace.trace(2,"Starting Conversion")
        self.io.digitalWrite(self.samplePin,self.io.LOW)
        #Need to hold low for at least 250 ns to start conversion
        #Start Busy Work
        busyWork+=5
        busyWork*=5
        sleep(0.01)
        #Busy work done
        self.io.digitalWrite(self.samplePin,self.io.HIGH)
        #Then need to wait approx 600 ns, intPin will go low,
        #indicating conversion done
        


        while(self.io.digitalRead(self.intPin)!=self.io.LOW):
            #Start Busy Work
            busyWork*=3
            busyWork+=2
            busyWork*=10
            if(busyWork>=1000):
                busyWork=1
            sleep(0.01)
            #Stop Busy Work

        #Conversion now done, and value will be held on output pins
